﻿using EmoneyWeiXinCommon;
using EmoneyWeiXinEntity;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace EmoneyWeiXinBLL
{
    /// <summary>
    /// 获取个股数据
    /// </summary>
    public class StockRule
    {
        private StockEntity _obj;
        public StockEntity obj
        {
            get
            {
                return _obj;
            }
        }

        private string _code;
        public StockRule(string c)
        {
            _code = c;
            _obj = new StockEntity();
        }
        public void getPic(int w, int h)
        {
            _obj.pic = Config.WeiXin_hq_pic + "_id=" + _code + "&t=1&p=2&i=vol&w=" + w.ToString() + "&h=" + h.ToString() + "&c=16";
        }
        public bool getStockPrice()
        {
            if (_code.StartsWith("6"))
            {
                _code = "0" + _code;
            }
            else
            {
                _code = "1" + _code;
            }
            string json = NetHelper.LoadData(Config.WeiXin_cms + "hangqing/GetLiveHangQingKeys.ashx?sn=" + _code, null, NetHelper.ENCODE_GBK);
            List<StockPrice> list = JsonTools.ToObject<List<StockPrice>>(json);
            if (list == null || list.Count == 0)
            {
                _obj.obj = null;
                return false;
            }
            else
            {
                _obj.obj = list[0];
                return true;
            }
        }
        public bool getStockPrice(string sn)
        {
            string key = CacheManager.GetCachedKey("hq." + sn);
            StockPrice objhq = CacheManager.RedisCache.Get<StockPrice>(key);
            if (objhq == null)
            {
                //string json = NetHelper.LoadData(System.Configuration.ConfigurationManager.AppSettings["StockPrice"].ToString() + "?sn=" + sn, null, NetHelper.ENCODE_GBK);
                string url = Config.WeiXin_cms + "hangqing/GetLiveHangQingKeys.ashx";
                string json = NetHelper.LoadData(url + "?sn=" + sn, null, NetHelper.ENCODE_GBK);
                List<StockPrice> list = JsonTools.ToObject<List<StockPrice>>(json);
                if (list == null || list.Count == 0)
                {
                    _obj.obj = new StockPrice();
                    return false;
                }
                else
                {
                    _obj.obj = list[0];
                    //存缓存
                    if (_obj.obj != null)
                    {
                        CacheManager.RedisCache.Set<StockPrice>(key, _obj.obj, 5);
                    }
                    return true;
                }
            }
            else
            {
                _obj.obj = objhq;
                return true;
            }

        }
        public static List<StockPrice> GetStockInfoList(string code)
        {
            string json = NetHelper.LoadData(Config.WeiXin_cms + "hangqing/GetLiveHangQingKeys.ashx?sn=" + code, null, NetHelper.ENCODE_GBK);
            List<StockPrice> list = JsonTools.ToObject<List<StockPrice>>(json);
            return list;
        }
        /// <summary>
        /// 获取个股资讯详情
        /// </summary>
        /// <param name="newsid"></param>
        /// <returns></returns>
        public PzzjEntity getStockNewsInfo(string newsid)
        {
            string url = string.Concat(Config.WeiXin_webapi_url, "News/api/Stock.GetNewsDetails?appid=", Config.WeiXin_webapi_appid);
            url = url + "&newsid=" + newsid;
            url = WebApiHelper.CreateUrl(url, Config.WeiXin_webapi_key);
            string result = NetHelper.LoadData(url, null);
            StockNews list = null;
            //result = "{"RetCode":"0","RetMsg":null,"Message":{"F035D_12001":"2013-08-02T13:00:40","F007V_12001":"retwer","F006V_12006":null,"F011V_12001":null,"F023V_12001":null,"F027V_12001":null,"f004v_12001":"3","FF0":0.0,"FF1":0.0,"FF2":0.0,"FF3":0.0,"C1":null,"N":null,"C":null,"T":null,"TT":null,"P":0.0,"F":0.0,"O":0.0,"Y":0.0,"D":0.0,"SY":null,"SYR":null,"A":null,"I":0.0,"F5":0.0,"GY":null,"F3M":0.0,"F1Y":0.0,"NewsId_Num":798657,"code":"3070102"}}";
            //result = "{\"RetCode\":\"-104100002\",\"RetMsg\":\"newsid不合法\",\"Message\":\"null\"}";

            if (!string.IsNullOrEmpty(result))
            {
                list = JsonTools.ToObject<StockNews>(result);
            }
            if (list == null)
            {
                return new PzzjEntity();
            }
            else
            {
                if (list.Message != null)
                    return list.Message;
                else
                    return new PzzjEntity();
            }
        }
        /// <summary>
        /// 获取个股资讯列表
        /// </summary>
        /// <param name="stockcode"></param>
        /// <returns></returns>
        public List<PzzjEntity> getStockNewsList(string stockcode)
        {
            string keynew = CacheManager.GetCachedKey("stocknewslists." + stockcode);
            List<PzzjEntity> objnew = CacheManager.RedisCache.Get<List<PzzjEntity>>(keynew);
            if (objnew != null) return objnew;
            else
            {
                string url = string.Concat(Config.WeiXin_webapi_url, "News/api/Stock.GetStockNewsList?appid=", Config.WeiXin_webapi_appid);
                url = url + "&code=" + stockcode;
                url = WebApiHelper.CreateUrl(url, Config.WeiXin_webapi_key);
                //MyTrace.get().add("getStockNewsList." + url);
                string result = NetHelper.LoadData(url, null);
                LogManager.DefaultLogger.Debug("SendSms url:" + url);
                LogManager.DefaultLogger.Debug("SendSms result:" + result);

                StockNewsLists list = null;
                if (!string.IsNullOrEmpty(result))
                {
                    list = JsonTools.ToObject<StockNewsLists>(result);
                }
                if (list == null)
                {
                    objnew = new List<PzzjEntity>();
                }
                else
                {
                    //存缓存
                    if (list.Message != null)
                    {
                        List<PzzjEntity> tmp = list.Message.OrderByDescending(x => x.F035D_12001).Take(3).ToList<PzzjEntity>();
                        CacheManager.RedisCache.Set<List<PzzjEntity>>(keynew, tmp, 2 * 60);
                        objnew = tmp;
                    }
                    else objnew = new List<PzzjEntity>();
                }
            }
            return objnew;
        }

        /// <summary>
        /// 自选股股票代码,eg:1234567,600011,600001,1,5(上证 6位     深圳 前面加1  7位     指数1位  )
        /// </summary>
        /// <param name="userid"></param>
        /// <returns></returns>
        public string getOptionalStocks(string userid)
        {
            string url = string.Concat(Config.WeiXin_optional_url, "getzxg.ashx?appid=", Config.WeiXin_optional_appid);
            url = url + "&userid=" + userid + "&zxgtype=.";
            url = WebApiHelper.CreateUrl(url, Config.WeiXin_optional_key);
            string result = NetHelper.LoadData(url, null);
            OptionEntity op = JsonTools.ToObject<OptionEntity>(result);
            if (op != null)
            {
                result = op.stocks;
            }
            return result;
        }

        /// <summary>
        /// 转化为7位的股票代码字符串，用“，”隔开eg：0000001,1234567
        /// </summary>
        /// <param name="stocks"></param>
        /// <returns></returns>
        public string Convert7StockString(string stocks)
        {
            //if (!string.IsNullOrEmpty(stocks))
            //{
            //    stocks = stocks.Replace(';', ',');
            //    var s = stocks.Split(',');
            //    var ss = "";
            //    foreach (var t in s)
            //    {
            //        var t1 = "";
            //        if (t.Length == 6)
            //        {
            //            t1 = '0' + t;//默认+0
            //            GpdmInfo gpinfo = Gpdm.GetGpdmInfo(t.ToString());
            //            if (gpinfo != null)
            //                t1 = gpinfo.Station.ToString() + t.ToString();//6位股票代码前面加上市场变成7位股票代码
            //        }
            //        else if (t.Length == 1)//指数
            //        {
            //            t1 = "000000" + t;
            //        }
            //        else
            //        {
            //            t1 = t;
            //        }
            //        ss = ss + t1 + ',';
            //    }
            //    ss = ss.Trim(',');
            //    stocks = string.Join(",", ss.Split(',').Distinct().ToArray());
            //}
            //return stocks;
            Security secu = new Security();
            WeiXinReplyRule wrrule = new WeiXinReplyRule();
            secu = wrrule.GetAllStocks().FirstOrDefault(x => x.SecuCode == stocks); if (secu.SecuMarket == "012002" || secu.SecuMarket == "012003" || secu.SecuMarket == "012015")
            {
                stocks = "1" + stocks;
            }
            else
            {
                stocks = "0" + stocks;
            }
            return stocks;
        }

        /// <summary>
        /// 转化为6位的股票代码字符串，用“，”隔开eg：000001,123456
        /// </summary>
        /// <param name="stocks"></param>
        /// <returns></returns>
        private string Convert6StockString(string stocks)
        {
            if (!string.IsNullOrEmpty(stocks))
            {
                stocks = stocks.Replace(';', ',');
                var s = stocks.Split(',');
                var ss = "";
                foreach (var t in s)
                {
                    var t1 = "";
                    if (t.Length == 7)
                    {
                        t1 = t.Substring(1, 6);
                    }
                    else
                    {
                        t1 = t;
                    }
                    ss = ss + t1 + ',';
                }
                ss = ss.Trim(',');
                stocks = string.Join(",", ss.Split(',').Distinct().ToArray());
            }

            return stocks;
        }
        /// <summary>
        /// 判断是否是我的自选股
        /// </summary>
        /// <param name="userid"></param>
        /// <param name="stockcode">上证6位，深圳7位，指数1位</param>
        /// <returns></returns>
        public bool IsMyStock(string userid, string stockcode)
        {
            if (userid == "") return false;
            var b = false;
            var re = getOptionalStocks(userid).Split(';');//因为刘小勇提供的接口返回数据有6位，有7位股票代码
            if (re.Contains(stockcode))
                b = true;
            return b;
        }


        public static bool isStockCode(string str)
        {
            return str == "600111";
        }
        /// <summary>
        /// 添加或者删除自选股op=1删除自选股，否则添加自选股
        /// </summary>
        /// <param name="userid"></param>
        /// <param name="stockcode"></param>
        /// <param name="op"></param>
        /// <returns></returns>
        //public string OpMyStock(string userid, string stockcode, string op)
        //{
        //    var iRe = "0";
        //    try
        //    {
        //        //var userid = Request["istockid"];
        //        //var stockcode = Request["stockcode"];
        //        //var op = Request["op"];
        //        if (!string.IsNullOrEmpty(userid) && !string.IsNullOrEmpty(stockcode))
        //        {
        //            //StockRule sr = new StockRule("");
        //            var p = this.OpOptionalStock(userid, stockcode, op);

        //            if (p != null)
        //            {
        //                if (p.resultcode == "0")
        //                {
        //                    iRe = "1";//成功
        //                }
        //                else
        //                {
        //                    iRe = p.resultmsg;
        //                }
        //            }
        //        }
        //        else
        //        {
        //            iRe = "参数传递错误";
        //        }
        //    }
        //    catch (Exception ex)
        //    {
        //        iRe = "操作自选股失败";
        //        LogManager.DefaultLogger.Error(ThinkDev.Logging.LogConvert.ParseWebEx(ex), string.Format("AjaxControllers下OpOptionalStock方法异常！"));
        //    }
        //    return iRe;
        //}

    }
}
